<script setup>
import { inject, onMounted, ref } from 'vue'
//图标
import { IconArrowLeft } from '../icon/index.js'
import DlLoading from '../components/DlLoading.vue'
import { DlMessageBox } from '../util/messagebox.js';

//引入 api
import { findUserOneOrderFun, modifyOrderAddrFun, userOrderPayFun } from '../api/order.js'

//主菜单核心
const menuCore = inject('menuCore');
//返回
function doGoBack() {
    menuCore.back();
}
//订单状态 1~7
const statusNameArr = ['未知', '待付款', '待发货', '待收货', '待评价', '已完成', '已删除', '已取消'];
const orderStatusTxt = ref('');

//当前登录用户的订单-待支付
const userOrder = ref({});
const loading = ref(false);
const isNeedPay = ref(false);//是否需要付款
const currentAddr = ref({name:'', phone:'', addr:''});//用于编辑
function doLoadData() {
    if(orderId !== null) {//存在订单
        loading.value = true;
        //获取对应订单信息
        let params = {
            orderId: orderId
        };
        console.log('params:', params);

        if (window && window.enableDl) {
            //模拟
            setTimeout(()=>{
                let order = {
                    id: orderId, no: 'xxxxxxxxxxxxxxxxxxxxxx1', totalPrice: '229.95', totalNum: 5, status: 1, details: [
                        {id: 11, productId:1, title:'测试商品11测试商品11测试商品11测试商品11测试商品11', image:'./product.jpg', price:99.99, num:2, type:'xxx'},
                        {id: 12, productId:2, title:'测试商品22', image:'./product.jpg', price:9.99, num:3, type:'sssxxxxxxxaaaasssswwwxxxxxaqw'},
                    ], name:'汤姆', phone:'12345678901', addr: '江苏南京江北新区XXX社区XX路NN号SSSS',
                    //订单失效时间
                    expireTime: Date.now()+180000
                };

                //成功后执行以下操作
                userOrder.value = order;
                currentAddr.value = {name: order.name, phone: order.phone, addr: order.addr};
                loading.value = false;

                if(order.status == 1) {
                    isNeedPay.value = true;
                    //未支付, 则显示支付倒计时
                    countDownTime();
                    cdTimer.value = setInterval(()=>{
                        countDownTime();
                    }, 1000);
                } else {
                    isNeedPay.value = false;
                    expired.value = true;
                }
                let txt = statusNameArr[order.status];
                orderStatusTxt.value = txt ? ('订单状态: '+txt) : '无效订单';
            }, 1000);
        } else {
            //请求api
            findUserOneOrderFun(orderId).then((result)=>{
                console.log('findUserOneOrderFun result:', result);
                if (result.code == 200) {
                    DlMessageBox.success(result.msg);
                    let order = result.data;
                    //成功后执行以下操作
                    userOrder.value = order;
                    currentAddr.value = {name: order.name, phone: order.phone, addr: order.addr};
                    if(order.status == 1) {
                        isNeedPay.value = true;
                        //未支付, 则显示支付倒计时
                        countDownTime();
                        cdTimer.value = setInterval(()=>{
                            countDownTime();
                        }, 1000);
                    } else {
                        isNeedPay.value = false;
                        expired.value = true;
                    }
                    let txt = statusNameArr[order.status];
                    orderStatusTxt.value = txt ? ('订单状态: '+txt) : '无效订单';
                } else {
                    DlMessageBox.error(result.msg);
                }
                loading.value = false;
            });
        }
    }
}

//地址编辑
const addrEditFlag = ref(false);//是否处于编辑状态
function doShowModifyAddr() {
    addrEditFlag.value = true;
    let order = userOrder.value;
    currentAddr.value = {name: order.name, phone: order.phone, addr: order.addr};
}
function doHideModifyAddr() {
    addrEditFlag.value = false;
    let order = userOrder.value;
    currentAddr.value = {name: order.name, phone: order.phone, addr: order.addr};
}
//修改订单地址信息
function doModifyCurrentAddr() {
    let order = userOrder.value;
    //修改后地址
    let ca = currentAddr.value;
    let params = {
        orderId: order.id,
        name: ca.name,
        phone: ca.phone,
        addr: ca.addr,
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        order.name = params.name;
        order.phone = params.phone;
        order.addr = params.addr;
        addrEditFlag.value = false;
    } else {
        //请求api
        modifyOrderAddrFun(params.orderId, params.name, params.phone, params.addr).then((result)=>{
            console.log('result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);

                order.name = params.name;
                order.phone = params.phone;
                order.addr = params.addr;
            } else {
                DlMessageBox.error(result.msg);
            }
            addrEditFlag.value = false;
        });
    }
}

//支付倒计时处理
const cdShowTxt = ref('');
const cdTimer = ref();
const expired = ref(false);
function countDownTime() {
    //剩余时间
    let t = userOrder.value.expireTime - Date.now();
    if(t <= 0) {//活动结束, 停止倒计时
        clearInterval(cdTimer.value);
        cdShowTxt.value = `订单已失效`;
        expired.value = true;
        return;
    }
    //剩余时间 转换为 时分秒
    let h = Math.trunc(t / (60*60*1000));
    let m = Math.trunc( (t % (60*60*1000)) / (60*1000) );
    let s = Math.trunc( (t % (60*1000)) / 1000 );
    if(m < 10) m = '0'+m;
    if(s < 10) s = '0'+s;
    cdShowTxt.value = `剩余时间: ${h}:${m}:${s}`;
}

//支付方式
const payTypeArr = ref([
    {key: 1, name: '支付宝', image: './alipay.jpg'},
    {key: 2, name: '微信', image: './weixinpay.jpg'},
    {key: 3, name: '银联', image: './unionpay.jpg'},
]);
//选择的支付方式
const paySelected = ref(1);

//确认支付
function doOrderPay() {
    let status = userOrder.value.status;
    //状态校验
    switch(status) {
        case 1:// 待付款
            break;
        case 2:
        case 3:
        case 4: 
        case 5: 
            DlMessageBox.warning('该订单已付款');
            return;
        case 6: 
            DlMessageBox.warning('该订单已删除');
            return;
        case 7: 
            DlMessageBox.warning('该订单已失效');
            return;
        default:
            DlMessageBox.warning('该订单已失效');
            return;
    }
    if(expired.value) {
        DlMessageBox.warning('订单已失效');
        return;
    }

    //模拟支付(服务端修改订单状态为 2)
    //支付方式 1 支付宝, 2 微信, 3 银联 等
    console.log('paySelected:', paySelected.value);
    console.log('order:', userOrder.value);

    if (window && window.enableDl) {
        //模拟
        //成功后执行以下操作
        DlMessageBox.success('支付成功');
        // menuCore.push('/order');
    } else {
        //请求api
        userOrderPayFun(userOrder.value.id, paySelected.value).then((result)=>{
            console.log('result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后执行以下操作
                menuCore.push('/order');
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }    
}

//当前订单id
let orderId = null;
onMounted(()=>{
    let id = parseInt(localStorage.getItem('orderId'));
    if(!isNaN(id)) {
        orderId = id;
    }

    doLoadData();
});

</script>
<template>
    <div class="view-dl">
        <!-- 顶部 -->
        <div class="top-head-dl">
            <IconArrowLeft class="back-icon" @click="doGoBack" />
            <div class="title-dl">订单支付</div>
        </div>

        <div class="view-body-dl" v-show="!loading">
            <div class="order-list-dl">
                <!-- 支付倒计时 -->
                <div class="coun-down-box-dl">
                    <span>{{cdShowTxt}}</span>
                    <span v-show="!isNeedPay" >{{orderStatusTxt}}</span>
                </div>

                <!-- 收货信息 -->
                <div class="order-label-dl">收件信息</div>
                <div class="addr-box-dl">
                    <div class="user-box-dl" v-show="!addrEditFlag" >
                        <div class="name-dl">{{userOrder.name}}</div>
                        <div class="phone-dl">{{userOrder.phone}}</div>
                    </div>
                    <div class="addr-dl" v-show="!addrEditFlag" >{{userOrder.addr}}</div>

                    <div class="user-box-dl" v-show="addrEditFlag" >
                        <input type="text" class="input-dl name-input-dl" v-model="currentAddr.name">
                        <input type="text" class="input-dl phone-input-dl" v-model="currentAddr.phone">
                    </div>
                    <textarea class="addr-area-dl" v-show="addrEditFlag" v-model="currentAddr.addr"></textarea>

                    <div class="addr-select-dl" >
                        <div class="btn-dl" v-show="!addrEditFlag" @click="doShowModifyAddr" >修改</div>
                        <div class="btn-dl" v-show="addrEditFlag" @click="doModifyCurrentAddr" >确定</div>
                        <div class="btn-dl" v-show="addrEditFlag" @click="doHideModifyAddr" >取消</div>
                    </div>
                </div>

                <div class="order-label-dl">订单信息</div>
                <div class="order-info-dl">
                    <div class="order-no-dl">
                        <span class="tip-dl" >订单编号:</span>
                        <span class="no-dl">{{userOrder.no}}</span>
                    </div>
                    <div class="order-price-dl">
                        <span class="tip-dl" >支付金额:</span>
                        <span class="price-dl" >￥{{userOrder.totalPrice}}</span>
                    </div>
                </div>

                <!-- 详情 -->
                <div class="order-label-dl">商品信息</div>
                <div class="detail-list-dl">
                    <div class="detail-box-dl" v-for="d in userOrder.details" :key="d.id">
                        <div class="img-box-dl">
                            <img :src="d.image" alt="no image">
                        </div>
                        <div class="desc-box-dl" >
                            <div class="product-title-dl">{{d.title}}</div>
                            <div class="product-type-dl">规格: {{d.type}}</div>
                        </div>
                        <div class="right-box-dl" >
                            <div class="price-dl">￥{{d.price}}</div>
                            <div class="num-dl">x {{d.num}}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="pay-type-list-dl" v-show="isNeedPay" >
                <div class="pay-label-dl">支付方式</div>
                <label class="pay-type-box-dl" v-for="p in payTypeArr" :key="p.key">
                    <input type="radio" class="radio-dl" :value="p.key" v-model="paySelected">
                    <div class="pay-img-dl">
                        <img :src="p.image" alt="">
                    </div>
                    <div class="pay-title-dl">{{p.name}}</div>
                </label>
            </div>

            <div class="btn-list-dl" v-show="isNeedPay">
                <div class="pay-btn-dl" @click="doOrderPay" >确定支付</div>
            </div>
        </div>

        <div class="load-box-dl" v-show="loading" >
            <DlLoading style="font-size: 1rem" />
        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    height: 100%;
    overflow: hidden auto;
}
.top-head-dl {
    background-color: #fff;
    color: #333;
    padding: 0.2rem;
    position: sticky;
    top: 0;
    z-index: 2;
}
.top-head-dl .back-icon {
    width: 0.8rem;
    height: 0.8rem;
    cursor: pointer;
    position: absolute;
    top: 50%;
    left: 0.2rem;
    transform: translate(0, -50%);
}
.top-head-dl .title-dl {
    font-size: 0.7rem;
    text-align: center;
}

.view-body-dl {
    padding: 0.2rem;
}

.order-list-dl {
    background-color: #fff;
    padding: 0.2rem;
    border-radius: 0.2rem;
}
.coun-down-box-dl {
    margin-bottom: 0.2rem;
    text-align: center;
    border-bottom: 1px solid #ccc;
    font-size: 0.32rem;
    padding: 0.2rem;
    color: #f00;
}
.order-label-dl {
    font-size: 0.48rem;
    color: #999;
    border-bottom: 1px solid #ccc;
    padding-bottom: 0.1rem;
}

.addr-box-dl {
    margin: 0.2rem 0;
    padding: 0.2rem;
    font-size: 0.4rem;
    background-color: #fff;
    color: #666;
    font-weight: bold;
    position: relative;
    padding-right: 1.2rem;
}
.user-box-dl {
    margin-bottom: 0.2rem;
}
.user-box-dl .name-dl {
    display: inline-block;
    margin-right: 0.6rem;
}
.user-box-dl .phone-dl {
    display: inline-block;
}
.addr-box-dl .addr-dl {
    margin-bottom: 0.2rem;
    word-break: break-all;
}
.addr-select-dl {
    width: 1rem;
    text-align: right;
    color: #999;
    position: absolute;
    top: 50%;
    right: 0.2rem;
    transform: translateY(-50%);
    cursor: pointer;
}
.addr-select-dl .btn-dl {
    margin: 0.1rem 0;
}

.addr-box-dl .input-dl {
    font-size: 0.4rem;
    border-radius: 0.1rem;
    padding: 0.1rem;
    box-sizing: border-box;
}
.addr-box-dl .name-input-dl {
    width: 35%;
    margin-right: 0.2rem;
}
.addr-box-dl .phone-input-dl {
    width: 45%;
}
.addr-box-dl .addr-area-dl {
    width: 100%;
    height: 1.4rem;
    font-size: 0.4rem;
    border-radius: 0.1rem;
    padding: 0.1rem;
    box-sizing: border-box;
    background-color: #fff;
    color: #333;
    resize: none;
}

.detail-list-dl {
    background-color: #fff;
    border-radius: 0.2rem;
    color: #999;
    padding: 0.2rem;
}
.detail-box-dl {
    display: flex;
}
.img-box-dl {
    flex-shrink: 0;
    width: 2rem;
    height: 2rem;
    margin: 0.1rem 0;
}
.img-box-dl img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.4rem;
    display: block;
}
.desc-box-dl {
    flex: 1 1 auto;
    margin-left: 0.2rem;
    overflow: hidden;
}
.desc-box-dl .product-title-dl {
    color: #333;
    margin-bottom: 0.1rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.desc-box-dl .product-type-dl {
    font-size: 0.36rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.right-box-dl {
    flex-shrink: 0;
    text-align: right;
}
.right-box-dl .price-dl {
    color: #d00;
    font-weight: bold;
    margin-bottom: 0.1rem;
}
.right-box-dl .num-dl {
    font-size: 0.36rem;
}

.order-info-dl {
    padding: 0.2rem;
    color: #666;
    font-size: 0.4rem;
    font-weight: bold;
    margin: 0.2rem 0;
}
.order-no-dl {
    margin-bottom: 0.2rem;
}
.order-info-dl .tip-dl {
    margin-right: 0.2rem;
}
.order-info-dl .no-dl {
    font-size: 0.38rem;
    color: #999;
}
.order-info-dl .price-dl {
    color: #d00;
}

.pay-type-list-dl {
    margin: 0.2rem 0;
    padding: 0.2rem;
    background-color: #fff;
    border-radius: 0.2rem;
    color: #999;
}
.pay-label-dl {
    font-size: 0.48rem;
    border-bottom: 1px solid #ccc;
    padding-bottom: 0.1rem;
}
.pay-type-box-dl {
    display: flex;
    height: 1.2rem;
    align-items: center;
}
.pay-type-box-dl .radio-dl {
    width: 0.6rem;
    height: 0.6rem;
    flex-shrink: 0;
    margin-right: 0.4rem;
    cursor: pointer;
}
.pay-type-box-dl .pay-img-dl {
    width: 0.8rem;
    height: 0.8rem;
    flex-shrink: 0;
    margin-right: 0.2rem;
}
.pay-img-dl img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.24rem;
    display: block;
}
.pay-type-box-dl .pay-title-dl {
    flex: 1 1 auto;
    font-size: 0.52rem;
    color: #333;
}

.btn-list-dl {
    text-align: center;
    margin: 0.2rem;
}
.pay-btn-dl {
    font-size: 0.6rem;
    color: #fff;
    background-color: #900000;
    padding: 0.1rem 0.8rem;
    border-radius: 0.6rem;
    display: inline-block;
    cursor: pointer;
    user-select: none;
}

.load-box-dl {
    text-align: center;
    color: #aaa;
    margin: 0.2rem;
}
.load-box-dl .no-more-data-dl {
    font-size: 0.4rem;
    border-top: 1px solid #ccc;
    padding-top: 0.2rem;
}

</style>